<template>
  <div class="theme-switcher">
    <div class="theme-dropdown" @click="toggleDropdown" ref="dropdownRef">
      <div class="theme-icon">
        {{ currentThemeIcon }}
      </div>
      <span class="theme-name">{{ currentThemeName }}</span>
      <span class="dropdown-arrow" :class="{ 'is-open': isOpen }">▼</span>
    </div>
    
    <div v-if="isOpen" class="theme-dropdown-menu">
      <div 
        v-for="theme in themes" 
        :key="theme.value"
        class="theme-option"
        :class="{ 'is-active': currentTheme === theme.value }"
        @click="selectTheme(theme.value)"
      >
        <span class="theme-option-icon">{{ theme.icon }}</span>
        <span class="theme-option-name">{{ theme.name }}</span>
        <span v-if="currentTheme === theme.value" class="theme-option-check">✓</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'

// 主题配置
const themes = [
  {
    value: 'light',
    name: '明亮主题',
    icon: '☀️'
  },
  {
    value: 'dark',
    name: '暗黑主题',
    icon: '🌙'
  },
  {
    value: 'sepia',
    name: '护眼主题',
    icon: '🍃'
  },
  {
    value: 'high-contrast',
    name: '高对比度',
    icon: '⚡'
  }
]

const currentTheme = ref('light')
const isOpen = ref(false)
const dropdownRef = ref(null)

// 计算当前主题信息
const currentThemeIcon = computed(() => {
  return themes.find(t => t.value === currentTheme.value)?.icon || '☀️'
})

const currentThemeName = computed(() => {
  return themes.find(t => t.value === currentTheme.value)?.name || '明亮主题'
})

// 切换下拉菜单
const toggleDropdown = () => {
  isOpen.value = !isOpen.value
}

// 选择主题
const selectTheme = (themeValue) => {
  currentTheme.value = themeValue
  applyTheme(themeValue)
  saveTheme(themeValue)
  isOpen.value = false
}

// 应用主题
const applyTheme = (themeValue) => {
  // 移除所有主题类
  document.documentElement.classList.remove('theme-light', 'theme-dark', 'theme-sepia', 'theme-high-contrast')
  
  // 添加新主题类
  document.documentElement.classList.add(`theme-${themeValue}`)
  
  // 触发自定义事件
  window.dispatchEvent(new CustomEvent('themeChange', { detail: { theme: themeValue } }))
}

// 保存主题到localStorage
const saveTheme = (themeValue) => {
  try {
    localStorage.setItem('theme', themeValue)
  } catch (error) {
    console.warn('无法保存主题设置:', error)
  }
}

// 从localStorage加载主题
const loadTheme = () => {
  try {
    const savedTheme = localStorage.getItem('theme')
    if (savedTheme && themes.some(t => t.value === savedTheme)) {
      currentTheme.value = savedTheme
      applyTheme(savedTheme)
      return
    }
  } catch (error) {
    console.warn('无法加载主题设置:', error)
  }
  
  // 检测系统主题偏好
  detectSystemTheme()
}

// 检测系统主题
const detectSystemTheme = () => {
  if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
    currentTheme.value = 'dark'
    applyTheme('dark')
  } else {
    currentTheme.value = 'light'
    applyTheme('light')
  }
}

// 点击外部关闭下拉菜单
const handleClickOutside = (event) => {
  if (dropdownRef.value && !dropdownRef.value.contains(event.target)) {
    isOpen.value = false
  }
}

// 监听系统主题变化
const handleSystemThemeChange = (e) => {
  const savedTheme = localStorage.getItem('theme')
  if (!savedTheme) {
    const newTheme = e.matches ? 'dark' : 'light'
    currentTheme.value = newTheme
    applyTheme(newTheme)
  }
}

onMounted(() => {
  loadTheme()
  document.addEventListener('click', handleClickOutside)
  
  // 监听系统主题变化
  if (window.matchMedia) {
    const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)')
    darkModeQuery.addEventListener('change', handleSystemThemeChange)
  }
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  
  if (window.matchMedia) {
    const darkModeQuery = window.matchMedia('(prefers-color-scheme: dark)')
    darkModeQuery.removeEventListener('change', handleSystemThemeChange)
  }
})
</script>

<style scoped>
.theme-switcher {
  position: relative;
  display: inline-block;
}

.theme-dropdown {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background: var(--vp-c-bg-soft);
  border: 1px solid var(--vp-c-border);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
}

.theme-dropdown:hover {
  background: var(--vp-c-bg-mute);
  border-color: var(--vp-c-brand);
}

.theme-icon {
  font-size: 1.2rem;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
}

.theme-name {
  font-size: 0.9rem;
  color: var(--vp-c-text-1);
  font-weight: 500;
}

.dropdown-arrow {
  font-size: 0.8rem;
  color: var(--vp-c-text-2);
  transition: transform 0.3s ease;
}

.dropdown-arrow.is-open {
  transform: rotate(180deg);
}

.theme-dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 0.5rem;
  min-width: 200px;
  background: var(--vp-c-bg);
  border: 1px solid var(--vp-c-border);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  overflow: hidden;
}

.theme-option {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  padding: 0.75rem 1rem;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
}

.theme-option:hover {
  background: var(--vp-c-bg-soft);
}

.theme-option.is-active {
  background: var(--vp-c-brand-dimm);
  color: var(--vp-c-brand);
}

.theme-option-icon {
  font-size: 1.1rem;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.theme-option-name {
  flex: 1;
  font-size: 0.9rem;
  color: var(--vp-c-text-1);
}

.theme-option.is-active .theme-option-name {
  color: var(--vp-c-brand);
  font-weight: 500;
}

.theme-option-check {
  font-size: 0.9rem;
  color: var(--vp-c-brand);
  font-weight: bold;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .theme-dropdown {
    padding: 0.4rem 0.8rem;
  }
  
  .theme-name {
    font-size: 0.8rem;
  }
  
  .theme-dropdown-menu {
    min-width: 180px;
    right: -1rem;
  }
  
  .theme-option {
    padding: 0.6rem 0.8rem;
  }
}

/* 平滑过渡动画 */
:root {
  --theme-transition-duration: 0.3s;
}

.theme-switcher * {
  transition: background-color var(--theme-transition-duration) ease,
              border-color var(--theme-transition-duration) ease,
              color var(--theme-transition-duration) ease,
              transform var(--theme-transition-duration) ease;
}
</style>